<template>
  <view class="container">
    <!-- 顶部筛选栏 -->
    <view class="filter-bar">
      <view
        class="filter-item"
        v-for="(item, index) in filterOptions"
        :key="index"
        :class="{ active: currentFilter === item.value }"
        @click="switchFilter(item.value)"
      >
        {{ item.label }}
      </view>
    </view>
    <!-- 内容区域使用swiper实现左右滑动 -->
    <swiper
      class="swiper-container"
      :current="currentFilterIndex"
      @change="handleSwiperChange"
      :duration="300"
    >
      <swiper-item v-for="(item, index) in filterOptions" :key="index">
        <scroll-view
          scroll-y
          class="scroll-container"
          @scrolltolower="handleScrollToLower"
          refresher-enabled
          :refresher-triggered="refresherTriggered"
          @refresherrefresh="handleRefresh"
          refresher-threshold="80"
          refresher-background="#f5f5f5"
          @scroll="handleScroll"
        >
          <!-- 加载中提示 -->
          <view
            class="loading-container"
            v-if="
              articlesByFilter[item.value].length === 0 &&
              loadingStatus[item.value]
            "
          >
            <FeatherIcon
              name="loader"
              size="42"
              color="#999"
              class="loading-icon"
            />
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 空数据提示 -->
          <view
            class="empty-container"
            v-else-if="
              articlesByFilter[item.value].length === 0 &&
              !loadingStatus[item.value]
            "
          >
            <FeatherIcon name="inbox" size="64" color="#999" />
            <text class="empty-text">暂无数据，点击刷新</text>
            <button
              size="mini"
              type="default"
              @click="loadArticles(item.value)"
              class="refresh-btn"
            >
              刷新
            </button>
          </view>

          <!-- 帖子列表 -->
          <view class="article-list" v-else>
            <view
              class="article-item"
              v-for="article in articlesByFilter[item.value]"
              :key="article.oId"
              :class="{
                'sticky-article': isSticky(article),
                'global-sticky': isGlobalSticky(article),
              }"
              @click="navigateToDetail(article.oId)"
            >
              <!-- 置顶标识 -->
              <view class="sticky-tag" v-if="isSticky(article)">
                {{ getStickyLevel(article) }}
              </view>

              <view class="article-header">
                <image
                  class="author-avatar"
                  :src="article.articleAuthor.userAvatarURL"
                  mode="aspectFill"
                ></image>
                <view class="article-meta">
                  <text class="author-name">{{
                    article.articleAuthor.userNickname ||
                    article.articleAuthor.userName
                  }}</text>
                  <text class="publish-time">{{ article.timeAgo }}</text>
                </view>
              </view>

              <view class="article-content">
                <text
                  class="article-title"
                  :class="{ 'sticky-title': isSticky(article) }"
                  >{{ article.articleTitle }}</text
                >
                <text class="article-summary">{{
                  formatSummary(article.articlePreviewContent)
                }}</text>

                <!-- 帖子图片 -->
                <image
                  v-if="article.articleThumbnailURL"
                  :src="article.articleThumbnailURL"
                  mode="aspectFill"
                  class="article-image"
                ></image>
              </view>

              <view class="article-footer">
                <view
                  class="article-tags"
                  v-if="article.articleTags && article.articleTags.length > 0"
                >
                  <text
                    class="tag"
                    v-for="(tag, tagIndex) in formatTags(article.articleTags)"
                    :key="tagIndex"
                    >{{ tag }}</text
                  >
                </view>
                <view class="stat-group">
                  <view class="stat-item">
                    <FeatherIcon name="eye" size="16" color="#999" />
                    <text class="stat-value">{{
                      article.articleViewCount
                    }}</text>
                  </view>
                  <view class="stat-item">
                    <FeatherIcon name="message-circle" size="16" color="#999" />
                    <text class="stat-value">{{
                      article.articleCommentCount
                    }}</text>
                  </view>
                  <view class="stat-item">
                    <FeatherIcon name="thumbs-up" size="16" color="#999" />
                    <text class="stat-value">{{ article.articleGoodCnt }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 加载更多区域 -->
          <view
            class="loading-more"
            v-if="articlesByFilter[item.value].length > 0"
          >
            <view class="loading-content" v-if="loadingStatus[item.value]">
              <FeatherIcon
                name="loader"
                size="36"
                color="#999"
                class="loading-icon"
              />
              <text>加载中...</text>
            </view>
            <view
              class="loading-content"
              v-else-if="!hasMoreStatus[item.value]"
            >
              <FeatherIcon name="check-circle" size="36" color="#999" />
              <text>已经到底了~</text>
            </view>
            <view class="loading-content" v-else @click="loadMore(item.value)">
              <FeatherIcon name="more-horizontal" size="36" color="#999" />
              <text class="load-more-text">点击加载更多</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
    <!-- 添加发帖按钮 -->
    <view
      class="post-button"
      @click="navigateToPost"
      :class="{ hidden: isScrolling }"
    >
      <FeatherIcon name="plus" size="32" color="#fff" />
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from "vue";
import {
  timeAgo,
  htmlToText,
  showLoading,
  hideLoading,
  showError,
} from "@/utils/common.js";
import api from "@/api";
import FeatherIcon from "@/components/FeatherIcon.vue";

// 添加调试输出
console.log("页面初始化");

// 滚动控制
const isScrolling = ref(false);
let scrollTimer = null;

// 筛选选项
const filterOptions = [
  { label: "最新", value: "recent" },
  { label: "热门", value: "hot" },
  { label: "点赞", value: "good" },
  { label: "最近回复", value: "reply" },
];

// 当前选中的筛选
const currentFilter = ref("recent");

// 获取当前筛选选项的索引
const currentFilterIndex = computed(() => {
  return filterOptions.findIndex((item) => item.value === currentFilter.value);
});

// 文章列表数据 - 按筛选类型分类
const articlesByFilter = reactive({
  recent: [],
  hot: [],
  good: [],
  reply: [],
});

// 每种筛选类型的页码
const pageByFilter = reactive({
  recent: 1,
  hot: 1,
  good: 1,
  reply: 1,
});

// 加载状态
const loadingStatus = reactive({
  recent: false,
  hot: false,
  good: false,
  reply: false,
});

// 是否有更多数据
const hasMoreStatus = reactive({
  recent: true,
  hot: true,
  good: true,
  reply: true,
});

// 下拉刷新状态
const refresherTriggered = ref(false);

// 移除测试模式
const showTestList = ref(false);

// 格式化时间显示
const formatTime = (timestamp) => {
  return timeAgo(timestamp);
};

// 格式化文章摘要
const formatSummary = (html) => {
  return htmlToText(html, 100);
};

// 格式化标签
const formatTags = (tagString) => {
  if (!tagString) return [];
  return tagString.split(",").slice(0, 3); // 最多显示3个标签
};

// 判断文章是否置顶
const isSticky = (article) => {
  // 检查置顶状态和置顶剩余时间
  return article && article.articleStick > 0 && article.articleStickRemains > 0;
};

// 判断是否是全局置顶
const isGlobalSticky = (article) => {
  return article && article.articleStick >= 9000000000000000;
};

// 获取置顶等级
const getStickyLevel = (article) => {
  // 置顶级别显示：articleStick值特别大时为全局置顶，较小值为普通置顶
  if (article.articleStick >= 9000000000000000) {
    return "长期置顶";
  } else {
    return "置顶";
  }
};

// 切换筛选方式
const switchFilter = (filter) => {
  if (currentFilter.value === filter) return;
  console.log("切换到筛选类型:", filter);
  currentFilter.value = filter;

  // 如果该分类下还没有数据，加载数据
  if (articlesByFilter[filter].length === 0) {
    console.log("该分类无数据，开始加载数据");
    loadArticles(filter);
  } else {
    console.log("该分类已有数据，数量:", articlesByFilter[filter].length);
  }
};

// 加载文章列表
const loadArticles = async (filter = currentFilter.value) => {
  if (loadingStatus[filter] || !hasMoreStatus[filter]) {
    console.log(
      "已在加载中或无更多数据，跳过加载",
      filter,
      loadingStatus[filter],
      hasMoreStatus[filter]
    );
    return;
  }

  try {
    console.log(
      "开始加载文章列表，类型:",
      filter,
      "页码:",
      pageByFilter[filter]
    );
    loadingStatus[filter] = true;

    let res;
    switch (filter) {
      case "hot":
        res = await api.article.getHotArticles(pageByFilter[filter]);
        break;
      case "good":
        res = await api.article.getGoodArticles(pageByFilter[filter]);
        break;
      case "recent":
        res = await api.article.getRecentArticles(pageByFilter[filter]);
        break;
      case "reply":
        res = await api.article.getRecentReplyArticles(pageByFilter[filter]);
        break;
    }

    console.log("API返回结果:", res);

    if (res && res.code === 0) {
      const newArticles = res.data.articles || [];
      console.log("获取到文章数量:", newArticles.length);
      // 更新文章列表
      articlesByFilter[filter] = [...articlesByFilter[filter], ...newArticles];
      // 判断是否还有更多数据
      if (newArticles.length < 10) {
        hasMoreStatus[filter] = false;
        console.log("无更多数据");
      } else {
        pageByFilter[filter]++;
        console.log("页码递增为:", pageByFilter[filter]);
      }
    } else {
      console.error("API返回错误:", res?.msg || "未知错误");
      showError(res?.msg || "获取文章列表失败");
    }
  } catch (error) {
    console.error("加载文章失败", error);
    showError("加载失败，请稍后重试");
  } finally {
    loadingStatus[filter] = false;
    hideLoading();
    console.log("加载状态复位，当前文章数量:", articlesByFilter[filter].length);
  }
};

// 加载更多
const loadMore = (filter) => {
  console.log("手动加载更多");
  loadArticles(filter);
};

// 跳转到文章详情页
const navigateToDetail = (articleId) => {
  uni.navigateTo({
    url: `/pages/article/detail?id=${articleId}`,
  });
};

// 滑动切换处理
const handleSwiperChange = (e) => {
  const index = e.detail.current;
  console.log("滑动切换到索引:", index);
  const newFilter = filterOptions[index].value;

  // 只有在过滤器真正变化时才执行switchFilter
  if (currentFilter.value !== newFilter) {
    switchFilter(newFilter);
  }
};

// 滚动到底部加载更多
const handleScrollToLower = () => {
  console.log("滚动到底部");
  loadMore(currentFilter.value);
};

// 下拉刷新处理
const handleRefresh = async () => {
  try {
    console.log("触发下拉刷新");
    refresherTriggered.value = true;

    // 重置当前筛选类型的数据
    pageByFilter[currentFilter.value] = 1;
    hasMoreStatus[currentFilter.value] = true;
    articlesByFilter[currentFilter.value] = [];

    // 重新加载数据
    await loadArticles(currentFilter.value);
  } catch (error) {
    console.error("刷新出错:", error);
  } finally {
    // 结束刷新状态
    setTimeout(() => {
      refresherTriggered.value = false;
      console.log("刷新完成，关闭刷新状态");
    }, 500);
  }
};

// 处理滚动事件
const handleScroll = () => {
  isScrolling.value = true;

  // 清除之前的定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer);
  }

  // 设置新的定时器，滚动停止500ms后显示按钮
  scrollTimer = setTimeout(() => {
    isScrolling.value = false;
  }, 500);
};

// 手动强制加载数据
const forceLoadData = () => {
  console.log("强制加载数据");
  // 重置当前选择的类型数据
  pageByFilter[currentFilter.value] = 1;
  hasMoreStatus[currentFilter.value] = true;
  articlesByFilter[currentFilter.value] = [];
  loadArticles(currentFilter.value);
};

// 清除所有数据并重新加载
const resetAllData = () => {
  // 重置所有数据
  Object.keys(articlesByFilter).forEach((key) => {
    articlesByFilter[key] = [];
    pageByFilter[key] = 1;
    hasMoreStatus[key] = true;
  });

  // 加载当前标签数据
  loadArticles(currentFilter.value);
};

// 跳转到发帖页面
const navigateToPost = () => {
  uni.navigateTo({
    url: "/pages/article/post",
  });
};

// 页面加载
onMounted(() => {
  console.log("组件挂载完成");

  // 清除所有缓存数据并重新加载
  resetAllData();

  // 延迟一段时间后检查是否有数据，如果没有则重试
  setTimeout(() => {
    console.log(
      "延时检查数据情况:",
      articlesByFilter[currentFilter.value].length
    );
    if (articlesByFilter[currentFilter.value].length === 0) {
      console.log("延时后发现无数据，重试加载");
      loadArticles(currentFilter.value);
    }
  }, 2000);
});
</script>

<style lang="scss">
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.filter-bar {
  display: flex;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
  padding-top: 30px;
  flex-shrink: 0;

  .filter-item {
    padding: 20rpx 30rpx;
    font-size: 30rpx;
    color: #666;
    position: relative;

    &.active {
      color: #ff9800;
      font-weight: bold;

      &:after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background-color: #ff9800;
        border-radius: 2rpx;
      }
    }
  }
}

.swiper-container {
  flex: 1;
  height: 0; /* 关键：让它根据flex自动扩展高度 */
  width: 100%;
}

.scroll-container {
  height: 100%;
  width: 100%;
}

/* 加载中状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .loading-icon {
    animation: rotate 1s linear infinite;
    color: #ff9800;
  }

  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }
}

/* 空数据状态 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 0;

  .empty-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 20rpx;
  }

  .refresh-btn {
    margin-top: 20rpx;
  }
}

.article-list {
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;

  .article-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    position: relative;
    overflow: hidden;
  }

  .sticky-tag {
    position: absolute;
    right: 0;
    top: 0;
    background-color: #ff9800;
    color: white;
    font-size: 22rpx;
    padding: 6rpx 16rpx;
    border-radius: 0 0 0 16rpx;
    z-index: 10;
  }

  .article-header {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .author-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 16rpx;
      border: 2rpx solid #f0f0f0;
    }

    .article-meta {
      display: flex;
      flex-direction: column;
    }

    .author-name {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }

    .publish-time {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }
  .article-content {
    margin-bottom: 16rpx;

    .article-title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 12rpx;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .article-summary {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .article-image {
      width: 100%;
      height: 320rpx;
      border-radius: 12rpx;
      margin-top: 16rpx;
      background-color: #f0f0f0;
    }
  }

  .article-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #f5f5f5;
    padding-top: 16rpx;

    .article-tags {
      display: flex;
      flex-wrap: wrap;

      .tag {
        font-size: 22rpx;
        color: #ff9800;
        background-color: rgba(255, 152, 0, 0.1);
        padding: 4rpx 12rpx;
        border-radius: 6rpx;
        margin-right: 10rpx;
      }
    }

    .stat-group {
      display: flex;
      align-items: center;
    }

    .stat-item {
      display: flex;
      align-items: center;
      margin-right: 24rpx;

      &:last-child {
        margin-right: 0;
      }

      .stat-value {
        font-size: 22rpx;
        color: #999;
        margin-left: 6rpx;
      }
    }
  }
}

.loading-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 28rpx;

  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20rpx 0;
  }

  .loading-icon {
    animation: rotate 1s linear infinite;
  }

  .load-more-text {
    color: #999;
    margin-top: 10rpx;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 发帖按钮样式 */
.post-button {
  position: fixed;
  right: 30rpx;
  bottom: 80rpx;
  width: 100rpx;
  height: 100rpx;
  background-color: #ff9800;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
  z-index: 1000;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
  }

  &.hidden {
    opacity: 0;
    transform: translateX(150rpx);
    pointer-events: none;
  }
}
</style>
